//
//  MoreZiXunViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/5/10.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "MoreZiXunViewController.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "ZiXunModel.h"
#import "ZiXunTableViewCell.h"
#import "ZiXunViewController.h"
#define kZiXunList @"http://120.26.129.84/api/news/"

@interface MoreZiXunViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *moreZiXunTableView; // 更多资讯tableview
@property (nonatomic, strong) NSTimer *myTimer; // 检查请求是否超时
@property (nonatomic, assign) NSInteger numberOfTime; // 存储请求时间
@property (nonatomic, assign) NSInteger shouldPage; // 需要请求的page

@property (nonatomic, strong) NSMutableArray *currentPageZiXunArray; // 当前资讯的数组
@property (nonatomic, strong) NSMutableArray *allZiXunArray; // 所有资讯的数组



@end

@implementation MoreZiXunViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
}



- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    // 关闭动画
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
    // 关闭计时器
    [self.myTimer invalidate];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 布局
    [self addMySubview];
    // 检查网络并建立数据源
    [self searchNetAndAddData];
}

// navi的修改
- (void)changeNavigation
{
    self.navigationItem.title = @"更多咨询";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 布局
- (void)addMySubview
{
    self.moreZiXunTableView  = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.moreZiXunTableView.backgroundColor = [UIColor whiteColor];
    self.moreZiXunTableView.dataSource  = self;
    self.moreZiXunTableView.delegate = self;
    [self.view addSubview:_moreZiXunTableView];
    
    self.moreZiXunTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    // 初始化所有数据字典
    self.allZiXunArray = [NSMutableArray array];
}

#pragma mark - 检查网络并建立数据源
- (void)searchNetAndAddData
{
     self.shouldPage = 0;
    self.moreZiXunTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if ([[[NetStatusHandle shareHandle] getNetStatus] isEqualToString:@"YES"]) {
            // 说明有网络
            [self addData];
            // 建立计时器，计算是否超时
            self.myTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(goTime:) userInfo:nil repeats:YES];
  
            [[NSRunLoop currentRunLoop] addTimer:self.myTimer forMode:NSRunLoopCommonModes];
            self.numberOfTime = 0;
            // 开始动画
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];

        } else {
            
            NSLog(@"没有网络");
            // 添加提示框
            [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kNoNetRefresh ToView:self];
        }
    }];
    [self.moreZiXunTableView.header beginRefreshing];
}

#pragma mark - 计时器方法
- (void)goTime:(NSTimer *)timer
{
    self.numberOfTime++;
    NSLog(@"更多资讯请求时间= %ld", self.numberOfTime);
    if (self.numberOfTime > 10) {
        NSLog(@"更多资讯请求超时");
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        [self.moreZiXunTableView.header endRefreshing];
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kQingQiuChaoShiReFresh ToView:self];
    }
}

#pragma mark - 添加数据源
- (void)addData
{
    self.shouldPage++;
    NSLog(@"当前页 = %ld",self.shouldPage);
    NSString *urlString = [NSString stringWithFormat:@"%@?page=%ld", kZiXunList, self.shouldPage];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        // 关闭刷新
        [self.moreZiXunTableView.header endRefreshing];
        // 将计时器置为0
        self.numberOfTime = 0;
        [self.myTimer invalidate];
        // 结束动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        NSArray *dataArray = [responseObject valueForKey:@"data"];
        if (dataArray.count == 0) {
            return;
        }
        for (NSDictionary *tempDic in dataArray) {
            ZiXunModel *model = [[ZiXunModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.allZiXunArray insertObject:model atIndex:0];
        }
        NSLog(@"self.allZiXunArray = %@", self.allZiXunArray);
        [self.moreZiXunTableView reloadData];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"数据刷新失败");
        // 关闭动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kHuoQuDataShiBaiRefresh ToView:self];
        // 关闭刷新
        [self.moreZiXunTableView.header endRefreshing];
        // 暂停计时器
        [self.myTimer invalidate];
        self.numberOfTime = 0;
    }];
  
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allZiXunArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ziXunCell";
    ZiXunTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ZiXunTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.allZiXunArray.count > indexPath.row) {
        cell.model = self.allZiXunArray[indexPath.row];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85 * kAdjustParamater;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZiXunViewController *ziXunVC = [[ZiXunViewController alloc] init];
    if (self.allZiXunArray.count > indexPath.row) {
        ZiXunModel *model = self.allZiXunArray[indexPath.row];
        ziXunVC.ziXunID = [NSString stringWithFormat:@"%@", model.myZiXunId];
    }
    [self.navigationController pushViewController:ziXunVC animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat height = scrollView.frame.size.height;
    CGFloat contentYOffset = scrollView.contentOffset.y;
    CGFloat distanceFromBottom = scrollView.contentSize.height - contentYOffset;
    if (distanceFromBottom < height) {
        NSLog(@"底部");
        self.moreZiXunTableView.bounces = NO;
    }
    if (contentYOffset == 0) {
        NSLog(@"顶部");
        self.moreZiXunTableView.bounces = YES;

    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30 * kAdjustParamater)];
    footerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.07];
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30 * kAdjustParamater;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
